<template>
  <div class="window">
    <div>
      <div v-loading="loading" ref="msgList" class="msg-list" @scroll="scroll">
        <div v-if="noMore" class="noMore">---无更多历史消息---</div>
        <item @imgLoad="imgLoad" :online-id="$store.state.customer.user.openId"
              :key="item.id"
              v-for="(item) in $store.state.customer.chatList" :item="item">
        </item>
      </div>
    </div>
    <div>
      <div class="msg-menu">
        <upload-btn @success="sendMediaMsg($event,1)" type="image">
          <el-icon>
            <camera/>
          </el-icon>
          <span>图片</span>
        </upload-btn>
        <upload-btn @success="sendMediaMsg($event,2)" type="media">
          <el-icon>
            <video-camera/>
          </el-icon>
          <span>视频</span>
        </upload-btn>
      </div>
      <div class="msg-input">
        <el-input
            v-model="message"
            @keyup.ctrl.enter="sendTextMsg"
            @keyup.alt.enter="sendTextMsg"
            :rows="5"
            type="textarea"
            placeholder="按住 Ctrl + Enter 发送消息"
        >
        </el-input>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import UploadBtn from '@/components/Upload/uploadBtn.vue'
import Item from './item.vue'
import {IChatMessage} from "@/api/types/chat";
import {store} from "@/store";
import {ref, watch, nextTick} from "vue";
import {ElMessage} from "element-plus";
import {queryMessageList, sendKfMessage} from "@/api/customer";

// 发送媒体文件
const sendMediaMsg = (obj: { path: string[], images: string[] }, type: number) => {
  for (let i = 0; i < obj.path.length; i++) {
    const msg: IChatMessage = {
      message: obj.path[i],
      type: type
    }
    if (type === 2) {
      msg.message += "," + obj.images[i]
    }
    sendKfMessage(msg) // 发送
  }
}


const sendTextMsg = async () => {
  if (message.value === '') {
    ElMessage.warning('消息不能为空！')
    return
  }
  const msg: IChatMessage = {
    message: message.value,
    type: 0
  }
  await sendKfMessage(msg)
  message.value = ''
}

const msgList = ref<HTMLElement>()
const message = ref('')
const loading = ref(false)
watch(() => store.state.customer.chatUpdateId, () => {
  nextTick(() => {
    msgList.value!.scrollTop = msgList.value?.scrollHeight!
  })
})

const scroll = async () => {
  if (!noMore.value && !loading.value && msgList.value!.offsetHeight > 180 && msgList.value!.scrollTop <= 60) {
    // 小于8条 无须加载消息了
    if (store.state.customer.chatList.length < 8) {
      return
    }
    loading.value = true
    // 判断是否可以加载下一页
    const list = await queryMessageList({
      username: store.state.customer.activeUser!.username,
      time: store.state.customer.chatList[0]?.createTime
    })
    if (list.length === 0) {
      noMore.value = true
    } else {
      store.state.customer.chatTime = list[0].createTime!
      store.state.customer.chatList.unshift(...list)
    }
    loading.value = false
    // 修复滚动条停留最顶部，不触发滚动bug
    await nextTick(() => {
      if (msgList.value!.scrollTop === 0) {
        msgList.value!.scrollTop = 200
      }
    })
  }
}
// 是否存在更多历史数据
const noMore = ref(false)
watch(() => store.state.customer.activeUser, () => {
  noMore.value = false
})
const imgLoad = (top: number) => {
  if (top > msgList.value?.scrollHeight! - 200) {
    msgList.value!.scrollTop = msgList.value?.scrollHeight! + 9999
  }
}
</script>

<style lang="scss" scoped>
div.noMore {
  text-align: center;
  background: #ebeee4;
  color: slategrey;
  height: 30px;
  line-height: 30px;
  margin-bottom: 5px;
}

div.window {
  flex: 1;
  position: relative;
  display: flex;
  justify-content: flex-start;
  align-content: center;
  flex-direction: column;
  border: 1px #dadada solid;
  // 窗口
  & > div:nth-child(1) {
    padding: 2px;

    div.msg-title {
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #308ae5;
      color: #ffffff;
    }

    div.msg-list {
      overflow: auto;
      height: calc(100vh - 296px);
    }
  }

  // 控制台
  & > div:nth-child(2) {
    height: 160px;
    flex-shrink: 0;
    background: #dadada;

    div.msg-menu {
      height: 43px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      padding-left: 5px;
    }

    div.msg-msg {
      overflow: hidden;
    }
  }
}
</style>